// 📁 service/impl/UserServiceImpl.java (添加缺失的方法)
package com.library.management.service.impl;

import com.library.management.entity.User;
import com.library.management.enums.UserRole;
import com.library.management.enums.UserStatus;
import com.library.management.repository.UserRepository;
import com.library.management.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 用户服务实现类
 * 处理用户相关的业务逻辑实现
 */
@Service
@Transactional
@RequiredArgsConstructor
@Slf4j
public class UserServiceImpl implements UserService {

    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;

    // ========== BaseService 接口方法实现 ==========

    @Override
    public User save(User user) {
        log.info("保存用户: {}", user.getUsername());

        // 对新用户进行密码加密
        if (user.getId() == null && user.getPassword() != null) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        }

        return userRepository.save(user);
    }

    @Override
    public User update(Long id, User user) {
        log.info("更新用户: {}", id);

        User existingUser = getById(id);

        // 更新允许修改的字段
        existingUser.setRealName(user.getRealName());
        existingUser.setEmail(user.getEmail());
        existingUser.setPhone(user.getPhone());
        existingUser.setIdCard(user.getIdCard());
        existingUser.setAvatarUrl(user.getAvatarUrl());
        existingUser.setMaxBorrowCount(user.getMaxBorrowCount());

        return userRepository.save(existingUser);
    }

    @Override
    public void delete(Long id) {
        log.info("删除用户: {}", id);

        User user = getById(id);

        // 检查用户是否有未归还的图书
        if (getCurrentBorrowCount(id) > 0) {
            throw new RuntimeException("用户有未归还的图书，无法删除");
        }

        // 检查用户是否有未支付的罚款
        // 这里可以添加罚款检查逻辑

        userRepository.deleteById(id);
    }

    @Override
    public Optional<User> findById(Long id) {
        return userRepository.findById(id);
    }

    @Override
    public User getById(Long id) {
        return userRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("用户不存在: " + id));
    }

    @Override
    public List<User> findAll() {
        return userRepository.findAll();
    }

    @Override
    public Page<User> findAll(Pageable pageable) {
        return userRepository.findAll(pageable);
    }

    @Override
    public boolean exists(Long id) {
        return userRepository.existsById(id);
    }

    // ========== UserService 特定方法实现 ==========

    @Override
    public Optional<User> findByUsername(String username) {
        return userRepository.findByUsername(username);
    }

    @Override
    public Optional<User> findByEmail(String email) {
        return userRepository.findByEmail(email);
    }

    @Override
    public Optional<User> findByUsernameOrEmail(String username, String email) {
        return userRepository.findByUsernameOrEmail(username, email);
    }

    @Override
    public boolean existsByUsername(String username) {
        return userRepository.existsByUsername(username);
    }

    @Override
    public boolean existsByEmail(String email) {
        return userRepository.existsByEmail(email);
    }

    @Override
    public List<User> findByRole(UserRole role) {
        return userRepository.findByRole(role);
    }

    @Override
    public List<User> findByStatus(UserStatus status) {
        return userRepository.findByStatus(status);
    }

    @Override
    public Page<User> findByRole(UserRole role, Pageable pageable) {
        return userRepository.findByRole(role, pageable);
    }

    @Override
    public List<User> searchUsers(String keyword) {
        return userRepository.findByUsernameOrRealNameContaining(keyword);
    }

    @Override
    public User updateStatus(Long userId, UserStatus status) {
        log.info("更新用户状态: {} -> {}", userId, status);

        User user = getById(userId);
        user.setStatus(status);
        return userRepository.save(user);
    }

    @Override
    public User updateRole(Long userId, UserRole role) {
        log.info("更新用户角色: {} -> {}", userId, role);

        User user = getById(userId);
        user.setRole(role);
        return userRepository.save(user);
    }

    @Override
    public User updatePassword(Long userId, String newPassword) {
        log.info("更新用户密码: {}", userId);

        User user = getById(userId);
        user.setPassword(passwordEncoder.encode(newPassword));
        return userRepository.save(user);
    }

    @Override
    public boolean validatePassword(Long userId, String password) {
        User user = getById(userId);
        return passwordEncoder.matches(password, user.getPassword());
    }

    @Override
    public boolean canUserBorrowBook(Long userId) {
        User user = getById(userId);
        return user.getStatus() == UserStatus.ACTIVE &&
                getCurrentBorrowCount(userId) < user.getMaxBorrowCount();
    }

    @Override
    public long getCurrentBorrowCount(Long userId) {
        return userRepository.countCurrentBorrowsByUserId(userId);
    }

    @Override
    public long getTotalBorrowCount(Long userId) {
        return userRepository.countByUserId(userId);
    }

    @Override
    public List<User> findUsersAvailableForBorrowing() {
        return userRepository.findUsersAvailableForBorrowing();
    }

    @Override
    public List<User> findUsersWithUnpaidFines() {
        return userRepository.findUsersWithUnpaidFines();
    }

    @Override
    public long countByRole(UserRole role) {
        return userRepository.countByRole(role);
    }

    @Override
    public long countByStatus(UserStatus status) {
        return userRepository.countByStatus(status);
    }
}